package com.example.train.common.config.security.handler;

import cn.hutool.json.JSONUtil;
import com.example.train.common.base.model.ResponseBase;
import com.example.train.common.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当未登录或者token失效访问接口时，自定义的返回结果
 */
@Component
@Slf4j
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.error("commence auth error: {}", authException.getMessage());
        response.setCharacterEncoding(SysConstant.CHARACTER_ENCODING);
        response.setContentType(SysConstant.CONTENT_TYPE);
        response.getWriter().println(JSONUtil.parse(ResponseBase.unauthorized(authException.getMessage())));
        response.getWriter().flush();
    }
}
